package com.akkainaction.remote.event;

import akka.actor.UntypedActor;
import akka.remote.*;

/**
 * 监控Actor
 */
public class MonitorActor extends UntypedActor {

    @Override
    public void preStart() throws Exception {
        //假如要订阅与远程相关的任何事件，可以使用RemotingLifecycleEvent，它是远程的顶级事件。
        // 由于EventStream实现了SubchannelClassification分类器，所以可以监听到它的任何子级事件。
        getContext().system().eventStream().subscribe(getSelf(), RemotingLifecycleEvent.class);
    }

    @Override
    public void onReceive(Object msg) throws Exception {
        if (msg instanceof AssociatedEvent) {
            //与远程系统连接成功时，将触发该事件，事件信息中包含本地、远程地址
            AssociatedEvent ae = (AssociatedEvent) msg;
            System.out.println("连接成功:["+ae.getLocalAddress() + "-->" + ae.getRemoteAddress()+"]");
        } else if (msg instanceof DisassociatedEvent) {
            //与远程系统断开连接时，将触发该事件，事件信息中包含本地、远程地址
            DisassociatedEvent de = (DisassociatedEvent) msg;
            System.out.println("断开连接:["+de.getLocalAddress() + "-->" + de.getRemoteAddress() +"]");
        } else if (msg instanceof AssociationErrorEvent) {
            //当连接出现错误时，将触发该事件，事件信息除了包含本地、远程地址外，还包括错误信息
            AssociationErrorEvent aee = (AssociationErrorEvent) msg;
            System.out.println("连接错误:["+aee.getLocalAddress() + "-->" + aee.getRemoteAddress() + ",错误信息:" + aee.getCause()+"]");
        }else if(msg instanceof RemotingListenEvent){
            //当远程系统启动并监听端口时，将触发该事件，
            // 此时会在控制台打印 "Remoting now listens on addresses...."
            RemotingListenEvent rle= (RemotingListenEvent) msg;
            System.out.println("远程系统启动了监听:["+rle.listenAddresses()+"]");
        }else if(msg instanceof RemotingShutdownEvent){
            //当远程系统 shutdown 时，将触发该事件，此时会在控制台打印 "Remoting shu down"
            RemotingShutdownEvent rse= (RemotingShutdownEvent) msg;
            System.out.println("远程系统shutdown:["+rse+"]");
        }else if(msg instanceof ThisActorSystemQuarantinedEvent){
            //当前系统被远程系统隔离时，将触发该事件
            ThisActorSystemQuarantinedEvent tasqe= (ThisActorSystemQuarantinedEvent) msg;
            System.out.println("当前系统被远程系统隔离:["+tasqe+"]");
        }
    }


}
